package com.egdigital.allzic.ui.fragment;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserCategory;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Category;
import com.egdigital.allzic.service.DownloadState;
import com.egdigital.allzic.ui.activity.ActivityMain;
import com.egdigital.allzic.ui.adapter.AdapterCategory;
import com.egdigital.allzic.utils.NetworkManager;

public class FragmentTabCategory extends BaseMainFragment implements OnItemClickListener, OnClickListener, JsonCallBack {

	private static final String	TAG	= FragmentTabCategory.class.getSimpleName();	// log
	// class data
	private JsonParserCategory	mJsonParser;
	private SelectedMenu		mSelectedMenu;
	private AdapterCategory		mAdapter;
	//
	private ListView			mListView;
	private ScrollView			mLocationView;
	private Button				mMenuGenre;
	private Button				mMenuLocation;
	private RelativeLayout		mButtonInter;
	private RelativeLayout		mButtonNational;
	private RelativeLayout		mButtonLocal;
	// network ui
	protected ActivityMain		mParent;
	protected View				mView;

	enum SelectedMenu {
		BY_LOCATION, // location menu
		BY_GENRE // displays genre menu
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setSeletedMenu(SelectedMenu.BY_LOCATION);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_tab_category, container, false);
		mLoadingView = (RelativeLayout) mView.findViewById(R.id.fragment_category_loading);
		mReloadView = (LinearLayout) mView.findViewById(R.id.fragment_category_reload);
		mNoResultView = (TextView) mView.findViewById(R.id.fragment_category_noresult);
		//
		mListView = (ListView) mView.findViewById(R.id.fragment_category_list);
		mMenuGenre = (Button) mView.findViewById(R.id.fragment_category_genre);
		mMenuLocation = (Button) mView.findViewById(R.id.fragment_category_location);
		mButtonInter = (RelativeLayout) mView.findViewById(R.id.fragment_category_inter);
		mButtonNational = (RelativeLayout) mView.findViewById(R.id.fragment_category_national);
		mButtonLocal = (RelativeLayout) mView.findViewById(R.id.fragment_category_local);
		mLocationView = (ScrollView) mView.findViewById(R.id.fragment_category_scroll);
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		YoYo.with(Techniques.FadeIn).duration(500).playOn(mButtonInter);
		YoYo.with(Techniques.FadeIn).duration(700).playOn(mButtonNational);
		YoYo.with(Techniques.FadeIn).duration(900).playOn(mButtonLocal);
		mMenuGenre.setOnClickListener(this);
		mMenuLocation.setOnClickListener(this);
		mButtonInter.setOnClickListener(this);
		mButtonNational.setOnClickListener(this);
		mButtonLocal.setOnClickListener(this);
		mReloadView.setOnClickListener(this);
		mListView.setOnItemClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		mParent.mCategorySelected = false;
	}

	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		// if (!mParent.mCategorySelected) {
		// mParent.mCategorySelected = true;
		FragmentCategoryRadio fragment = new FragmentCategoryRadio();
		Bundle param = new Bundle();
		param.putParcelable("category", mParent.getmListCategory().get(position));
		fragment.setArguments(param);
		mParent.getSupportFragmentManager()
				.beginTransaction()
				.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_bottom)
				.add(R.id.fragment_category, fragment)
				.addToBackStack("1")
				.commit();
		// }
	}

	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.fragment_category_reload:
				try {
					loadData();
				} catch (Exception e) {
				}
				break;
			case R.id.fragment_category_location: // menu par localisation multi choix
				updateIhm(false);
				break;
			case R.id.fragment_category_genre: // menu par genre, chargement de la liste
				initDataLoad();
				updateIhm(true);
				break;
			case R.id.fragment_category_inter: // fragment international
				FragmentCategoryInternational fragmentCategoryInternational = new FragmentCategoryInternational();
				mParent.mExplorerSelected = true;
				Bundle bundle = new Bundle();
				bundle.putString("title", getString(R.string.fragment_category_inter));
				fragmentCategoryInternational.setArguments(bundle);
				getSherlockActivity().getSupportFragmentManager()
										.beginTransaction()
										.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_bottom)
										.add(R.id.fragment_category, fragmentCategoryInternational)
										.addToBackStack("" + ActivityMain.INDEX_EXPLORE)
										.commit();
				break;
			case R.id.fragment_category_national: // fragment national
				FragmentCategoryNational fragmentCategoryNational = new FragmentCategoryNational();
				mParent.mExplorerSelected = true;
				getSherlockActivity().getSupportFragmentManager()
										.beginTransaction()
										.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_bottom)
										.add(R.id.fragment_category, fragmentCategoryNational)
										.addToBackStack("" + ActivityMain.INDEX_EXPLORE)
										.commit();
				break;
			case R.id.fragment_category_local: // fragment local
				FragmentCategoryLocal fragmentCategoryLocal = new FragmentCategoryLocal();
				mParent.mExplorerSelected = true;
				getSherlockActivity().getSupportFragmentManager()
										.beginTransaction()
										.setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_bottom)
										.add(R.id.fragment_category, fragmentCategoryLocal)
										.addToBackStack("" + ActivityMain.INDEX_EXPLORE)
										.commit();
				break;
		}
	}

	/**
	 * fragment life cycle
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mParent = (ActivityMain) activity;
	}

	@Override
	public void onDetach() {
		mParent = null;
		super.onDetach();
	}

	private void initDataLoad() {
		mJsonParser = JsonParserCategory.getInstance();
		VolleyManager.init(mParent);
		mJsonParser.initAndStartRequestQueue();
		mJsonParser.setJsonCallBack((JsonCallBack) this);
		// launch data load for the first time
		if (mParent.getmListCategory() == null || mParent.getmListCategory().isEmpty()) {
			try {
				loadData();
			} catch (Exception e) {
				Log.e(TAG, "", e);
			}
		}
	}

	private void loadData() throws Exception {
		if (NetworkManager.isConnected(mParent.getApplicationContext())) {
			mJsonParser.extractJsonObjectData(getString(R.string.url_categories));
		} else {
			setReload(mListView);
		}
	}

	private void updateIhm(boolean genreSelected) {
		if (genreSelected && mSelectedMenu.equals(SelectedMenu.BY_LOCATION)) {
			mMenuGenre.setBackgroundResource(R.drawable.selector_blue_favorite_dark);
			mMenuLocation.setBackgroundResource(R.drawable.selector_blue_favorite);
			// Utils.crossfade(mListView, mLocationView, 100);
			mLocationView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
			setSeletedMenu(SelectedMenu.BY_GENRE);
		} else if (!genreSelected && mSelectedMenu.equals(SelectedMenu.BY_GENRE)) {
			mMenuGenre.setBackgroundResource(R.drawable.selector_blue_favorite);
			mMenuLocation.setBackgroundResource(R.drawable.selector_blue_favorite_dark);
			switch (mDownloadState) {
				case LOADED:
					// Utils.crossfade(mLocationView, mListView, 100);
					mListView.setVisibility(View.GONE);
					mLocationView.setVisibility(View.VISIBLE);
					break;
				case LOADING:
					// Utils.crossfade(mLocationView, mLoadingView, 100);
					mLoadingView.setVisibility(View.GONE);
					mLocationView.setVisibility(View.VISIBLE);
					break;
				case RETRY:
					// Utils.crossfade(mLocationView, mReloadView, 100);
					mReloadView.setVisibility(View.GONE);
					mLocationView.setVisibility(View.VISIBLE);
					break;
			}
			setSeletedMenu(SelectedMenu.BY_LOCATION);
		}
	}

	private void updateAdapter(List<Category> list) {
		if (mAdapter == null) {
			mAdapter = new AdapterCategory(mParent.getApplicationContext(), list);
		}
		mListView.setAdapter(mAdapter);
	}

	/**
	 * volley callback
	 */
	@Override
	public void downloadStarted() {
		if (getSelectedMenu() == SelectedMenu.BY_GENRE) {
			setLoading(mListView);
		}
	}

	@Override
	public void downloadPercent(int percent) {
		// do nothing
	}

	@Override
	public <T> void downloadCompleted(List<T> list) {
		if (mParent == null || list == null) {
			return;
		}
		if (!list.isEmpty()) { // got a result
			mParent.setmListCategory((List<Category>) list);
			// sort the list [a-z]
			Collections.sort(list, new Comparator<Object>() {

				public int compare(Object o1, Object o2) {
					Category p1 = (Category) o1;
					Category p2 = (Category) o2;
					return p1.getTitle().compareToIgnoreCase(p2.getTitle());
				}
			});
			updateAdapter((List<Category>) list);
			if (getSelectedMenu() == SelectedMenu.BY_GENRE) {
				setLoaded(mListView);
			}
			setmDownloadState(DownloadState.LOADED);
		} else { // got no result
			if (getSelectedMenu() == SelectedMenu.BY_GENRE) {
				setReload(mListView);
			}
		}
	}

	@Override
	public void downloadEndedWithError(VolleyError error) {
		if (getSelectedMenu() == SelectedMenu.BY_GENRE) {
			setReload(mListView);
		}
	}

	/**
	 * menu selection
	 */
	private void setSeletedMenu(SelectedMenu menu) {
		mSelectedMenu = menu;
	}

	private SelectedMenu getSelectedMenu() {
		return mSelectedMenu;
	}
}
